import axios from 'axios'
import { Toast } from "mint-ui";
import { Indicator } from "mint-ui";
// create an axios instance
const service = axios.create({
    //baseURL: 'api', // 在index.js里配置跨域
    // baseURL: 'http://221.207.19.231:8080',
    //baseURL: 'http://183.242.52.85',
    // baseURL: 'http://192.168.20.77:8080',
    //baseURL: 'http://61.157.227.58:8081',
    //baseURL: 'http://localhost:8090/',
    baseURL: process.env.NODE_ENV == 'development' ? "" : window.localStorage.baseUrl,
    headers: { "Content-Type": "application/json;charset=utf-8" }, //即将被发送的自定义请求头
    withCredentials: true, //表示跨域请求时是否需要使用凭证
    timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(

    config => {
        // Indicator.open({
        //     text: 'Loading...',
        //     spinnerType: 'fading-circle'
        // });
        if (!config.headers['token']) {
            config.headers['token'] = `${window.localStorage.getItem(
        'token'
      ) || ''}`;
        }
        return config;
    },
    err => Promise.reject(err => {
        return err
    })
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.status === 1) {
            Toast({
                message: res.message,
                position: "center",
                duration: 1000,
            });
            return Promise.reject('error')
        }
        if (res.status === 2) {
            return Promise.reject('error')
        }
        if (res.status === 3) {
            return Promise.reject('error')
        }
        if (res.status === 400) {
            return Promise.reject('error')
        }
        if (res.status === 403) {
            window.localStorage.removeItem("userInfo");
            window.localStorage.removeItem("token");
            setTimeout(() => {
                window.location = '#/login/'
            }, 1000)
            return Promise.reject('error')
        }
        if (res.status === 405) {
            return Promise.reject('error')
        }
        if (res.status === 406) {
            Toast({
                message: 'HTTP请求不合法,请求参数可能被篡改',
                position: "center",
                duration: 1000,
            });
            return Promise.reject('error')
        }
        if (res.status === 407) {
            return Promise.reject('error')
        }
        if (res.status === 408) {
            return Promise.reject('error')
        }

        return response
    }, error => {
        console.log('err' + error) // for debug 
            // Dialog.alert({
            //     title: '警告',
            //     message: '登录连接超时'
            //   });
        return Promise.reject(error)
    })

export default service